﻿using Handday.Erp.Core;
using Handday.Erp.Transfer.Enum;
using Handday.Erp.Transfer.Models;
using Handday.Erp.Transfer.Repositories;
using Handday.Erp.Transfer.WebApiClient;
using HandDay.Framework.Common.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Handday.Erp.Transfer.Services.Imp
{
    /// <summary>
    /// 8大交易数据推送执行服务
    /// </summary>
    public class EightTradingPublishExecuteService : IPublishExecuteService
    {
        private readonly BaseApiUrl _baseApiUrl;
        private readonly IEightTradingTransferRepository _eightTradingTransferRepository;
        private readonly IErpTransferClient _erpTransferClient;
        private readonly ILogger<EightTradingPublishExecuteService> _logger;

        /// <summary>
        /// ctor
        /// </summary>
        public EightTradingPublishExecuteService(
            BaseApiUrl baseApiUrl,
            IEightTradingTransferRepository eightTradingTransferRepository,
            IErpTransferClient erpTransferClient,
            ILogger<EightTradingPublishExecuteService> logger)
        {
            _baseApiUrl = baseApiUrl;
            _erpTransferClient = erpTransferClient;
            _eightTradingTransferRepository = eightTradingTransferRepository;
            _logger = logger;
        }

        /// <summary>
        /// 功能类型
        /// </summary>
        public ErpFeatureTypeEnum FeatureType => ErpFeatureTypeEnum.EightTrading;

        /// <summary>
        /// 完整的推送地址列表
        /// </summary>
        public Func<List<string>> PublishUrlList =>
            () =>
            {
                var urlList = new List<string>
                {
                    $"{_baseApiUrl.ErpjointApiUrl}customer/ErpDataCenterStatisticsSync"
                };
                return urlList;
            };

        /// <summary>
        /// 推送逻辑
        /// </summary>
        /// <param name="corpId">企业编号</param>
        /// <param name="dateTime">对应日期数据</param>
        public async Task<ServiceResult> ExecuteAsync(ulong corpId, DateTimeOffset dateTime)
        {
            var year = dateTime.Year;
            var month = dateTime.Month;
            var list = await _eightTradingTransferRepository.Where(m => m.Year == year && m.Month == month)
                .Select(m => new EightTradingTransferCrmDetailDto
                {
                    Ytotal = m.YearAmount,
                    Mtotal = m.MonthAmount,
                    PmTotal = m.LastMonthAmount,
                    LastTotal = m.LastAmount,
                    LastTime = m.LastTradingTime,
                    CustomerKey = m.CustomId.ToString(),
                    TransactionCount = (int)m.TradingCount,
                    Year = m.Year,
                    Month = m.Month
                })
                .ToListAsync();
            if (!list.Any())
            {
                _logger.LogInformation($"{nameof(EightTradingPublishExecuteService)},{corpId},未查询到数据，不执行推送");
                return ServiceResult.Succeed();
            }

            var data = new EightTradingCrmDto { CorpId = corpId, Data = list };
            foreach (var url in PublishUrlList())
            {
                try
                {
                    await _erpTransferClient.PublishEightTradingDataToCrmAsync(url, data);
                }
                catch { }
            }

            return ServiceResult.Succeed();
        }
    }
}